How do you copy a file from one location to another in C#?
How do you copy a file from one location to another in C#?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Anubhav Kumar
19-May-2025In C#, you can copy a file from one location to another using the
File.Copymethod from theSystem.IOnamespace.Syntax:
sourceFileName: Full path to the file you want to copy.destFileName: Full path where you want the file copied.overwrite(optional): Set totrueif you want to overwrite the destination file if it exists.Example 1: Copy without overwrite
This throws an exception if the destination file already exists.
Example 2: Copy with overwrite
This replaces the destination file if it already exists.
Exceptions to handle (optionally):
FileNotFoundException: If the source file doesn't exist.IOException: If the destination file exists andoverwriteisfalse.UnauthorizedAccessException: If access is denied (e.g., permissions).DirectoryNotFoundException: If the path is invalid.